#!/usr/bin/env python3


# built-ins

# site-packages
import numpy
import theano
import theano.tensor as T

# locals
from cnn import load_dataset
from mlp import HiddenLayer
from logreg import LogisticRegression
from lenet import LeNetConvPoolLayer

# globals & constants
X, Y = load_dataset('chars.pkl')  # 2320
# batch_size = 20
# index = numpy.arange(116)
batch_size = 2320
index = 0
learning_rate = 0.13

# tmp
train_set_x = X
train_set_y = Y


x = T.matrix('x')
y = T.ivector('y')
rng = numpy.random.RandomState()

layer0_input = x.reshape((batch_size, 1, 16, 16))
layer0 = LeNetConvPoolLayer(rng, input = layer0_input,
                            image_shape = (batch_size, 1, 16, 16),
                            filter_shape = (4, 1, 5, 5),  # (12, 12)
                            poolsize = (1, 1))  # not reduce
layer1 = LeNetConvPoolLayer(rng, input = layer0.output,
                            image_shape = (batch_size, 4, 12, 12),
                            filter_shape = (8, 4, 5, 5),  # (8, 8)
                            poolsize = (2, 2))
layer2_input = layer1.output.flatten(2)
layer2 = HiddenLayer(rng, input = layer2_input,
                     n_in = 8 * 4 * 4,
                     n_out = 500,
                     activation = T.tanh)
layer3 = LogisticRegression(input=layer2.output, n_in=500, n_out=23)


cost = layer3.negative_log_likelihood(y)

# # create a function to compute the mistakes that are made by the model
# test_model = theano.function(
#     [index],
#     layer3.errors(y),
#     givens={
#         x: test_set_x[index * batch_size: (index + 1) * batch_size],
#         y: test_set_y[index * batch_size: (index + 1) * batch_size]
#     }
# )

# validate_model = theano.function(
#     [index],
#     layer3.errors(y),
#     givens={
#         x: valid_set_x[index * batch_size: (index + 1) * batch_size],
#         y: valid_set_y[index * batch_size: (index + 1) * batch_size]
#     }
# )

# create a list of all model parameters to be fit by gradient descent
params = layer3.params + layer2.params + layer1.params + layer0.params

# create a list of gradients for all model parameters
grads = T.grad(cost, params)

# train_model is a function that updates the model parameters by
# SGD Since this model has many parameters, it would be tedious to
# manually create an update rule for each model parameter. We thus
# create the updates list by automatically looping over all
# (params[i], grads[i]) pairs.
updates = [
    (param_i, param_i - learning_rate * grad_i)
    for param_i, grad_i in zip(params, grads)
]

train_model = theano.function(
    [index],
    cost,
    updates=updates,
    givens={
        x: train_set_x[index * batch_size: (index + 1) * batch_size],
        y: train_set_y[index * batch_size: (index + 1) * batch_size]
    }
)
